/**
 * 高德地图API配置和工具方法
 * 
 * 使用前需要：
 * 1. 在高德地图开放平台申请API Key
 * 2. 配置域名白名单
 * 3. 替换下面的API_KEY
 */

// 高德地图Web API配置
const AMAP_CONFIG = {
  // 替换为你的高德地图API Key
  API_KEY: '68cb02a1b6107ada38b890133a2f47f8',
  // Web API基础URL
  BASE_URL: 'https://restapi.amap.com/v3',
  // 默认城市
  DEFAULT_CITY: '全国'
}

/**
 * 逆地理编码 - 根据坐标获取地址信息
 * @param {number} longitude 经度
 * @param {number} latitude 纬度
 * @returns {Promise} 返回地址信息
 */
export function getAddressByLocation(longitude, latitude) {
  return new Promise((resolve, reject) => {
    // 构建请求URL
    const url = `${AMAP_CONFIG.BASE_URL}/geocode/regeo`
    const params = {
      key: AMAP_CONFIG.API_KEY,
      location: `${longitude},${latitude}`,
      poitype: '',
      radius: 1000,
      extensions: 'base',
      batch: false,
      roadlevel: 0
    }
    
    // 构建查询字符串
    const queryString = Object.keys(params)
      .map(key => `${key}=${encodeURIComponent(params[key])}`)
      .join('&')
    
    // 发起请求
    uni.request({
      url: `${url}?${queryString}`,
      method: 'GET',
      success: (res) => {
        if (res.data.status === '1' && res.data.regeocode) {
          const regeocode = res.data.regeocode
          const result = {
            name: regeocode.formatted_address,
            address: regeocode.formatted_address,
            province: regeocode.addressComponent.province,
            city: regeocode.addressComponent.city,
            district: regeocode.addressComponent.district,
            township: regeocode.addressComponent.township,
            neighborhood: regeocode.addressComponent.neighborhood,
            building: regeocode.addressComponent.building,
            pois: regeocode.pois || []
          }
          resolve(result)
        } else {
          reject(new Error(res.data.info || '逆地理编码失败'))
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

/**
 * 地理编码 - 根据地址获取坐标
 * @param {string} address 地址
 * @param {string} city 城市（可选）
 * @returns {Promise} 返回坐标信息
 */
export function getLocationByAddress(address, city = AMAP_CONFIG.DEFAULT_CITY) {
  return new Promise((resolve, reject) => {
    const url = `${AMAP_CONFIG.BASE_URL}/geocode/geo`
    const params = {
      key: AMAP_CONFIG.API_KEY,
      address: address,
      city: city
    }
    
    const queryString = Object.keys(params)
      .map(key => `${key}=${encodeURIComponent(params[key])}`)
      .join('&')
    
    uni.request({
      url: `${url}?${queryString}`,
      method: 'GET',
      success: (res) => {
        if (res.data.status === '1' && res.data.geocodes && res.data.geocodes.length > 0) {
          const geocode = res.data.geocodes[0]
          const location = geocode.location.split(',')
          const result = {
            longitude: parseFloat(location[0]),
            latitude: parseFloat(location[1]),
            formatted_address: geocode.formatted_address,
            province: geocode.province,
            city: geocode.city,
            district: geocode.district,
            level: geocode.level
          }
          resolve(result)
        } else {
          reject(new Error(res.data.info || '地理编码失败'))
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

/**
 * POI搜索 - 搜索兴趣点
 * @param {string} keywords 关键词
 * @param {string} city 城市（可选）
 * @param {number} page 页码（可选）
 * @param {number} offset 每页数量（可选）
 * @returns {Promise} 返回搜索结果
 */
export function searchPOI(keywords, city = AMAP_CONFIG.DEFAULT_CITY, page = 1, offset = 20) {
  return new Promise((resolve, reject) => {
    const url = `${AMAP_CONFIG.BASE_URL}/place/text`
    const params = {
      key: AMAP_CONFIG.API_KEY,
      keywords: keywords,
      city: city,
      page: page,
      offset: offset,
      extensions: 'base'
    }
    
    const queryString = Object.keys(params)
      .map(key => `${key}=${encodeURIComponent(params[key])}`)
      .join('&')
    
    uni.request({
      url: `${url}?${queryString}`,
      method: 'GET',
      success: (res) => {
        if (res.data.status === '1') {
          const pois = res.data.pois || []
          const results = pois.map(poi => {
            const location = poi.location.split(',')
            return {
              id: poi.id,
              name: poi.name,
              type: poi.type,
              address: poi.address,
              longitude: parseFloat(location[0]),
              latitude: parseFloat(location[1]),
              distance: poi.distance,
              tel: poi.tel,
              province: poi.pname,
              city: poi.cityname,
              district: poi.adname
            }
          })
          resolve({
            results: results,
            count: res.data.count,
            info: res.data.info
          })
        } else {
          reject(new Error(res.data.info || 'POI搜索失败'))
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

/**
 * 周边搜索 - 搜索指定位置周边的POI
 * @param {number} longitude 经度
 * @param {number} latitude 纬度
 * @param {string} keywords 关键词（可选）
 * @param {number} radius 搜索半径（米，可选）
 * @param {number} page 页码（可选）
 * @param {number} offset 每页数量（可选）
 * @returns {Promise} 返回搜索结果
 */
export function searchAround(longitude, latitude, keywords = '', radius = 1000, page = 1, offset = 20) {
  return new Promise((resolve, reject) => {
    const url = `${AMAP_CONFIG.BASE_URL}/place/around`
    const params = {
      key: AMAP_CONFIG.API_KEY,
      location: `${longitude},${latitude}`,
      keywords: keywords,
      radius: radius,
      page: page,
      offset: offset,
      extensions: 'base'
    }
    
    const queryString = Object.keys(params)
      .map(key => `${key}=${encodeURIComponent(params[key])}`)
      .join('&')
    
    uni.request({
      url: `${url}?${queryString}`,
      method: 'GET',
      success: (res) => {
        if (res.data.status === '1') {
          const pois = res.data.pois || []
          const results = pois.map(poi => {
            const location = poi.location.split(',')
            return {
              id: poi.id,
              name: poi.name,
              type: poi.type,
              address: poi.address,
              longitude: parseFloat(location[0]),
              latitude: parseFloat(location[1]),
              distance: poi.distance,
              tel: poi.tel,
              province: poi.pname,
              city: poi.cityname,
              district: poi.adname
            }
          })
          resolve({
            results: results,
            count: res.data.count,
            info: res.data.info
          })
        } else {
          reject(new Error(res.data.info || '周边搜索失败'))
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

/**
 * 计算两点间距离
 * @param {number} lng1 起点经度
 * @param {number} lat1 起点纬度
 * @param {number} lng2 终点经度
 * @param {number} lat2 终点纬度
 * @returns {number} 距离（米）
 */
export function calculateDistance(lng1, lat1, lng2, lat2) {
  const radLat1 = lat1 * Math.PI / 180.0
  const radLat2 = lat2 * Math.PI / 180.0
  const a = radLat1 - radLat2
  const b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0
  let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
    Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)))
  s = s * 6378.137 // 地球半径
  s = Math.round(s * 10000) / 10 // 保留1位小数
  return s * 1000 // 转换为米
}

export default {
  getAddressByLocation,
  getLocationByAddress,
  searchPOI,
  searchAround,
  calculateDistance
} 